const MyApp = getApp();
const globalData = MyApp.globalData;
// 小程序激励广告
let rewardedVideoAd = null;
export default {
    data() {
        return {
            typelist: globalData.typelist,
            imageSrc: '',
            loadingBoxText: globalData.$t('common').loading,
            mainScrollHeight: 0,
            sysconfig: uni.getStorageSync('sys_config'),
            srcUrl: '',
            adInfo: uni.getStorageSync('adInfo'),
        };
    },
    computed: {
        i18n() {
            return globalData.$t;
        }
    },
    onLoad(params) {
        this.srcUrl = decodeURIComponent(params.url);
    },
    onShow() {
        let _this = this;
        _this.tabIndex = uni.getStorageSync('tabIndex') || 0;
    },
    onReady() {
        this.initPage();
        this.imageSrc = decodeURIComponent(this.srcUrl);
    },
    methods: {
        loadend(){
            MyApp.closeLoading(this.$refs.loading);
        },
        initPage() {
            let _this = this;
            MyApp.showLoading(_this.$refs.loading);
            uni.getSystemInfo({
                success: res => {
                    let query = uni.createSelectorQuery().in(_this);
                    query.select('#navbar').boundingClientRect();
                    query.exec(re => {
                        let navbarHeight = re[0].height;
                        _this.mainScrollHeight = res.windowHeight - navbarHeight;
                        _this.initAd();
                    });
                }
            });
        },
        saveImg() {
            let _this = this;
            MyApp.showLoading(_this.$refs.loading);
            uni.getSetting({
                success(res) {
                    if (!res.authSetting['scope.writePhotosAlbum']) {
                        uni.authorize({
                            scope: 'scope.writePhotosAlbum',
                            success() {
                                //这里是用户同意授权后的回调
                                _this.showAd();
                            },
                            fail() {
                                //这里是用户拒绝授权后的回调
                                uni.showToast({
                                    title: '请在小程序设置里打开相册读写权限',
                                    icon: 'none'
                                });
                            }
                        });
                    } else {
                        //用户已经授权过了
                        _this.showAd();
                    }
                }
            });
        },
        initAd() {
            let _this = this;
            if (wx.createRewardedVideoAd && _this.adInfo && _this.adInfo.wallpaper_ad.length > 0) {
                rewardedVideoAd = wx.createRewardedVideoAd({
                    adUnitId: _this.adInfo.wallpaper_ad[_this.$func.randomNum(0, _this.adInfo.wallpaper_ad
                        .length - 1)].url
                });
                if (typeof rewardedVideoAd != 'undefined') {
                    rewardedVideoAd.onLoad(() => {
                        MyApp.closeLoading(_this.$refs.loading);
                        console.log('激励广告加载成功');
                    });
                    rewardedVideoAd.onError(err => {
                        MyApp.closeLoading(_this.$refs.loading);
                        // _this.downloadImg();
                        console.log('激励广告加载失败', err);
                        uni.showToast({
                            title: '该壁纸暂不可下载，请稍后再来',
                            icon: 'none',
                            success() {}
                        });
                    });
                    rewardedVideoAd.onClose(res => {
                        // 用户点击了【关闭广告】按钮
                        if (res && res.isEnded) {
                            // 正常播放结束，可以下发游戏奖励
                            uni.showModal({
                                title: '提示',
                                content: '长按保存图片',
                                showCancel: false,
                                success(res) {
                                    if (res.confirm) {
                                        _this.priviewImg();
                                    }
                                }
                            });
                        } else {
                            uni.showToast({
                                title: '看完广告即可免费下载',
                                icon: 'none'
                            });
                        }
                    });
                }
            }
        },
        showAd() {
            let _this = this;
            if (!_this.sysconfig.wallpaper_ad_lock) {
                uni.showModal({
                    title: '提示',
                    content: '长按保存图片',
                    showCancel: false,
                    success(res) {
                        if (res.confirm) {
                            MyApp.closeLoading(_this.$refs.loading);
                            _this.priviewImg();
                        }
                    }
                });
            } else {
                if (rewardedVideoAd) {
                    rewardedVideoAd.show().catch(() => {
                        rewardedVideoAd
                            .load()
                            .then(() => rewardedVideoAd.show())
                            .catch(err => {
                                MyApp.closeLoading(_this.$refs.loading);
                                uni.showToast({
                                    title: '该壁纸暂不可下载，请稍后再来',
                                    icon: 'none',
                                    success() {}
                                });
                            });
                    });
                }
            }
        },
        priviewImg() {
            let _this = this,
                tmp = [];
            tmp.push(_this.imageSrc);
            uni.previewImage({
                urls: tmp,
                longPressActions: {
                    success: function(data) {
                        console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
                    },
                    fail: function(err) {
                        console.log(err.errMsg);
                    }
                },
                complete(res) {
                    console.log(res);
                }
            });
        },
        downloadImg() {
            let _this = this;
            _this.loadingBoxText = globalData.$t('common').downloading;
            MyApp.showLoading(_this.$refs.loading);
            const downloadTask = uni.downloadFile({
                url: _this.imageSrc,
                success: res => {
                    MyApp.closeLoading(_this.$refs.loading);
                    if (res.statusCode === 200) {
                        uni.saveImageToPhotosAlbum({
                            filePath: res.tempFilePath,
                            success: function() {
                                uni.showToast({
                                    title: '已保存到相册',
                                    icon: 'none'
                                });
                            },
                            fail: function() {
                                uni.showToast({
                                    title: '保存失败， 请稍后重试',
                                    icon: 'none'
                                });
                            }
                        });
                    } else {
                        console.log(res);
                    }
                },
                complete: res => {
                    console.log(res);
                }
            });
            downloadTask.onProgressUpdate(res => {
                console.log('下载进度' + res.progress);
                console.log('已经下载的数据长度' + res.totalBytesWritten);
                console.log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite);
            });
        }
    }
};
